/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.click.app.webapp.action;

import com.click.app.model.Cart;
import com.click.app.model.Catalog;
import com.click.app.model.Category;
import com.click.app.model.LabelValue;
import com.click.app.model.Product;
import com.click.app.model.RequestClient;
import com.click.app.model.User;
import com.click.app.service.CartManager;
import com.click.app.service.CatalogManager;
import com.click.app.service.CategoryManager;
import com.click.app.service.GenericManager;
import com.click.app.service.ProductManager;
import com.click.app.service.RequestClientManager;
import com.click.app.service.UserManager;
import com.opensymphony.oscache.base.EntryRefreshPolicy;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 *
 * @author orgale
 */
public class RequestClientAction extends BaseAction {

    private CategoryManager categoryManager;
    private RequestClientManager requestClientManager;
    private ProductManager productManager;
    private CatalogManager catalogManager;
    private List categorys;
    private RequestClient requestClient;
    private Long id;
    private String name;
    private Product product;
    private CartManager cartManager;
    private Float quantity;
    private Long id_rowNum;
    private List<Category> listCategories;

    public void setId(Long id) {
        this.id = id;
    }

    public List<String> getProductNames() {
        List<String> names = new ArrayList<String>();
        List<Product> ps = productManager.getAll();

        for (Product p : ps) {
            names.add(p.getName());
        }

        return names;
    }

    public void setCartManager(CartManager cartManager) {
        this.cartManager = cartManager;
    }

    /*
    public boolean productsFree(Category dis) {
    boolean resp = true;

    List<Product> mats = productManager.getAll();
    for (Product m : mats) {
    for (Category d : m.getListCategorys()) {
    if (d.equals(dis)) {
    resp = false;

    }
    }
    }

    return resp;
    }
     */
    public String getItems() {
        Cart c = (Cart) getSession().getAttribute("cart");
        if (c != null) {
            return c.getTotalPrice().toString();
        }
        return "0.0";
    }

    public void setCatalogManager(CatalogManager catalogManager) {
        this.catalogManager = catalogManager;
    }

    public String listCatalog() {
        System.out.println("PortalAction -> listCatalog()");
        if (getRequest().getRemoteUser() != null) {
            User u = userManager.getUserByUsername(getRequest().getRemoteUser());
            getRequest().setAttribute("currentRole", u.getRoles().size());
        }
        Catalog catalog = catalogManager.findCurrentCatalog();
        if (catalog != null) {
            setListCategories(catalog.getCategorys());
        } else {
            setListCategories(new ArrayList<Category>());
        }
        for (Category category : getListCategories()) {
            System.out.println(category);
//            for (Product p : category.getProducts()) {
        //              System.out.println("\t" + p);
        //        }
        }
        System.out.println("PortalAction -> end listCatalog()");
        return SUCCESS;
    }

    public String delete() {
        System.out.println("deleting requestclient..." + getRequest().getParameter("row"));
        int index = Integer.parseInt(getRequest().getParameter("row"));
        Cart c = (Cart) getSession().getAttribute("cart");
        RequestClient rc = c.getRequests().get(index - 1);
        c.getRequests().remove(rc);
        c.setTotalPrice(c.getTotalPrice() - rc.getTotalPrice());

//        if (productsFree(category)) {
//        categoryManager.remove(new Long(category.getId()));
        saveMessage(getText("product.deleted"));
        //      } else {
        //          List messages = (List) getRequest().getSession().getAttribute("errors");
        //        if (messages == null) {
        //          messages = new ArrayList();
        //    }
        //        messages.add(getText("category.deleteError"));//
        //      getRequest().getSession().setAttribute("errors", messages);

        //     }
        return SUCCESS;
    }

    public List<LabelValue> getProductsNamesAndValues() {
        List<LabelValue> namesAndValues = new ArrayList<LabelValue>();
        List<Product> ps = productManager.getAll();

        for (Product p : ps) {
            namesAndValues.add(new LabelValue(p.getName(), p.getId().toString()));
        }
        return namesAndValues;

    }

    public LabelValue getPos(List<LabelValue> lp, Product pr) {
        for (LabelValue lv : lp) {
            if (pr.getName().matches(lv.getLabel()) && (pr.getId().toString().matches(lv.getValue()))) {
                return lv;
            }
        }
        return null;
    }

    public String edit() {
        getSession().setAttribute("view", null);
        listCatalog();
        System.out.println("editing request client...");
        //User user = userManager.getUserByUsername(getRequest().getRemoteUser());
        if (getRequest().getRemoteUser() != null) {
            product = productManager.get(id);
            requestClient = new RequestClient();
            requestClient.setDateRequestClient(new Date());
            requestClient.getProducts().add(product);
            requestClient.setPrice(productManager.getHighestPrice(product));
            getSession().setAttribute("requestClient", requestClient);
            return SUCCESS;
        } else {
            errorMessage(getText("login.error"));
            return ERROR;
        }

    }

    public String view() {
        listCatalog();
        System.out.println("viewingrequest client...");
        //User user = userManager.getUserByUsername(getRequest().getRemoteUser());
        product = productManager.get(id);
        requestClient = new RequestClient();
        requestClient.setDateRequestClient(new Date());
        requestClient.getProducts().add(product);
        requestClient.setPrice(productManager.getHighestPrice(product));
        getSession().setAttribute("requestClient", requestClient);
        getSession().setAttribute("view", true);
        return SUCCESS;

    }

    public String addToCart() {

        return SUCCESS;
    }
    /*
    public boolean validationPasses() {
    boolean vp = true;
    if (category.getName() == null || category.getName().matches("")) {
    //errorMessage("Campo requerido, nombre.");
    vp = false;
    }
    if (category.getDescription() == null || category.getDescription().matches("")) {
    //errorMessage("Campo requerido, valor.");
    vp = false;
    }
    System.out.println("val:"+vp);
    return vp;
    }
     */

    public String sar() throws Exception {
        System.out.println("hola mundo!");
        return SUCCESS;
    }

    public boolean haveCart(User user) {
        boolean resp = false;
        if (!cartManager.findCartByUser(user).isEmpty()) {
            resp = true;
        }
        return resp;
    }

    public String save() throws Exception {
        System.out.println("Saving requestClient...");
        if (cancel != null) {
            return CANCEL;
        }
        RequestClient rc = (RequestClient) getSession().getAttribute("requestClient");
        rc.setQuantity(requestClient.getQuantity());
        if (rc.getQuantity() > rc.getProduct().getStorageProduct().getStock()) {
            errorMessage("Not enough stock for your request.");
            return ERROR;
        }
        User u = userManager.getUserByUsername(getRequest().getRemoteUser());
        Cart cart;
        if ((Cart) getSession().getAttribute("cart") == null) {
            cart = new Cart();
            cart.setUser(u);
        } else {
            cart = (Cart) getSession().getAttribute("cart");

        }
        rc.setTotalPrice(rc.getQuantity() * rc.getPrice());
        rc.setCart(cart);
        cart.getRequests().add(rc);
        cart.setTotalPrice(cart.getTotalPrice() + (rc.getTotalPrice()));
        getSession().setAttribute("cart", cart);
        System.out.println("cart stored: " + cart);
        System.out.println("number of requests: " + cart.getRequests().size());
        System.out.println("cat's total price: " + cart.getTotalPrice());

        return SUCCESS;
    }

    public void setCategoryManager(CategoryManager categoryManager) {
        this.categoryManager = categoryManager;
    }

    public void setRequestClientManager(RequestClientManager requestClientManager) {
        this.requestClientManager = requestClientManager;
    }

    public void setProductManager(ProductManager productManager) {
        this.productManager = productManager;
    }

    public List getCategorys() {
        return categorys;
    }

    public String list() {
        categorys = categoryManager.getAll();
        return SUCCESS;
    }

    public String helpList() {
        return SUCCESS;
    }

    public String help() {
        return SUCCESS;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public String saveCategoryDescription() {
        System.out.println("NAME: " + name);
        System.out.println("id: " + getRequest().getAttribute("id"));
        System.out.println("d: " + getRequest().getAttribute("category"));

        return SUCCESS;
    }
    private String categoryName;
    private String categoryDescription;

    /**
     * @return the categoryName
     */
    public String getCategoryName() {
        return categoryName;
    }

    /**
     * @param categoryName the categoryName to set
     */
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    /**
     * @return the categoryDescription
     */
    public String getCategoryDescription() {
        return categoryDescription;
    }

    /**
     * @param categoryDescription the categoryDescription to set
     */
    public void setCategoryDescription(String categoryDescription) {
        this.categoryDescription = categoryDescription;
    }

    public List<Catalog> getCatalogs() {
        return catalogManager.getAll();
    }

    /**
     * @return the product
     */
    public Product getProduct() {
        return product;
    }

    /**
     * @param product the product to set
     */
    public void setProduct(Product product) {
        this.product = product;
    }

    /**
     * @return the requestClient
     */
    public RequestClient getRequestClient() {
        return requestClient;
    }

    /**
     * @param requestClient the requestClient to set
     */
    public void setRequestClient(RequestClient requestClient) {
        this.requestClient = requestClient;
    }

    /**
     * @return the quantity
     */
    public Float getQuantity() {
        return quantity;
    }

    /**
     * @param quantity the quantity to set
     */
    public void setQuantity(Float quantity) {
        this.quantity = quantity;
    }

    /**
     * @return the id_rowNum
     */
    public Long getId_rowNum() {
        return id_rowNum;
    }

    /**
     * @param id_rowNum the id_rowNum to set
     */
    public void setId_rowNum(Long id_rowNum) {
        this.id_rowNum = id_rowNum;
    }

    /**
     * @return the listCategories
     */
    public List<Category> getListCategories() {
        return listCategories;
    }

    /**
     * @param listCategories the listCategories to set
     */
    public void setListCategories(List<Category> listCategories) {
        this.listCategories = listCategories;
    }
}